import { messageConf } from "./gameWebSocketContent/messageConfig";
import superModule from "./superModule";

//
export class HandleMessage {
    [head: string]: (((data?: any) => void)[]);
}

export default class GameWebSocketModule extends superModule {

    protected m_className: string = 'webSocket网络模块';

    constructor() {
        super();
    }

    //地址
    private readonly m_socketUrl: string = 'ws://192.168.1.113:8288';
    private m_ws: WebSocket = null;
    //
    private m_message: HandleMessage = new HandleMessage();

    async preLoadModules(): Promise<void> {
        await super.preLoadModules();
    }

    async loadModule(): Promise<void> {
        //
        await super.loadModule();
    }

    //连接服务器
    async connectServer(): Promise<boolean> {
        return new Promise(resolve => {
            this.m_ws = new WebSocket(this.m_socketUrl);
            //
            this.m_ws.onclose = this.onWebsocketClose.bind(this);
            this.m_ws.onmessage = this.onWebsocketMessage.bind(this);
            this.m_ws.onerror = this.onWebsocketError.bind(this);
            //
            this.m_ws.onopen = (e) => {
                //
                this.onWebsocketOpen(e);
                //
                resolve(true);
            };
        })
    }

    addMessageOnEvent(head: string, callback: (data?: any) => void) {
        if (this.m_message[head] == null) {
            this.m_message[head] = [];
        }
        this.m_message[head].push(callback);
    }

    removeMessageEvent(head: string, callback: (data?: any) => void = null) {
        if (this.m_message[head] == null) return;

        if (callback == null) {
            this.m_message[head].length = 0;
        } else {
            let pos = this.m_message[head].indexOf(callback);
            if (pos >= 0) {
                this.m_message[head].splice(pos, 1);
            }
        }
    }
//电子邮件puhalskijsemen@gmail.com
//源码网站 开vpn全局模式打开 http://web3incubators.com/
//电报https://t.me/gamecode999

    disconnectServer() {
        if (this.m_ws && this.m_ws.readyState != this.m_ws.CLOSED && this.m_ws.readyState != this.m_ws.CLOSING) {
            this.m_ws.close();
        }
    }

    sendMessage(messageText: string): boolean {
        if (null == this.m_ws) {
            console.error('#48 未创建Websocket');
            return false;
        }
        if (this.m_ws.readyState != this.m_ws.OPEN) {
            console.warn('#52 与服务器的连接已断开');
            return false;
        }
        console.log('发送数据', messageText);
        this.m_ws.send(messageText);
        return true;
    }

    private onWebsocketOpen(e) {
        console.log('连接成功', e);
    }

    private onWebsocketClose(e) {
        console.log('服务器关闭', e);
    }

    private onWebsocketError(e) {
        console.log('服务器错误', e);
    }

    private onWebsocketMessage(e: MessageEvent) {
        console.log('服务器数据来临', e.data);
        let { head, body } = messageConf.unPackageMessage(e.data);
        let funcArray = this.m_message[head];
        //
        if (funcArray && funcArray.length > 0) {
            funcArray.forEach(callbackFn => {
                try {
                    callbackFn(body);
                } catch (e) {
                    console.error('#112 错误的回调处理');
                }
            })
        }
    }
}